<template>
  <div class="index-container pb-16 bg-gray-2600">
    <banner-top :aiNum="tool_count"
      :categoriesNum="category_count"></banner-top>
    <div class="index-content">
      <div class="max-w-11xl px-4 pt-5 pb-9 mx-auto">
        <index-menu-list></index-menu-list>
        <el-divider class="my-5"></el-divider>
        <index-categories-list :categories="category_group_list"></index-categories-list>

        <div class="mt-5 space-y-10">
          <div class="md:flex md:gap-5 items-start">
            <div class="md:flex-1">
              <tools-section :titleLabel="`${month}`"
                :year="`${year && year!==fullYear && !isYear ? `${year}` : ''}`"
                :isNoI18n="isYear"
                :isIndex="true"
                :toolsList="toolsList"
                v-loading="fLoading"
                :isFirstScreen="true">
                <common-square-sort :targetObj="sortOptions"
                  slot="sort"
                  :hasBorder="true"
                  :sort="sort"
                  selectType="sort"
                  class="block md:inline-block"
                  @toSearch="toSearch"></common-square-sort>
              </tools-section>
              <div class="w-2/4 mx-auto mt-16 text-center"
                v-if="toolsList && toolsList.length>0">
                <el-button type="text"
                  v-if="toolsList && toolsList.length>0 && next_page_url && !fLoading"
                  class="cursor-default">
                  <img src="@/static/images/loading.png"
                    class="loading"
                    alt=""
                    srcset="">
                </el-button>

                <!-- <el-divider v-else>
              <el-button type="text"
                class="cursor-default"
                :loading="loading">{{ $t('end') }}</el-button>
            </el-divider> -->
              </div>
              <el-empty v-else
                :description="$t('noData')"></el-empty>

              <div id="end"></div>

              <tools-section titleLabel="index_justLaunched"
                path="/new"
                :isIndex="true"
                id="justLaunched"
                :toolsList="new_list">
                <div class="flex justify-center mt-8"
                  slot="ctrl">
                  <common-link path="/new"
                    class="inline-flex items-center justify-between h-12 px-6 border border-gray-1200 duration-100 hover:border-purple-1300 rounded-md group whitespace-nowrap">
                    <span class="text-base text-gray-1000 group-hover:text-purple-1300">
                      {{$t('index_discoverMoreNew')}}
                    </span>
                  </common-link>
                </div>
              </tools-section>
            </div>
            <div class="hidden md:block md:flex-shrink-0 w-sidebar"
              v-if="recommendToolsList && recommendToolsList.length > 0">
              <h3 class="text-34 text-gray-34 font-semibold">{{$t('category_featured')}}</h3>
              <div class="tools space-y-4 mt-7 px-3.5 py-4 bg-white rounded-lg">
                <min-tool-featured v-for="(item, key) in recommendToolsList"
                  :key="item.handle+'-'+key"
                  :toolPosIndex="key"
                  :toolsData="item"></min-tool-featured>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'MostSaved',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error, store }) {
    try {
      let created_at_start
      let created_at_end
      let month
      let isYear = false
      //获取月份简写
      const dateArr = params.handle.split('-')
      const year = parseInt(dateArr[1])
      if (dateArr && dateArr.length === 1) {
        month = dateArr[0]
        created_at_start = `${month}-01-01`
        created_at_end = `${month}-12-31`
        isYear = true
      } else {
        month =
          dateArr[0].substr(0, 3).charAt(0).toUpperCase() +
          dateArr[0].substr(1, 2)

        //获取时间范围
        const dateString = params.handle.replace('-', ' 01 ')
        created_at_start = moment(dateString, 'MMMM DD YYYY').format(
          'YYYY-MM-DD'
        )
        created_at_end = moment(dateString, 'MMMM DD YYYY')
          .endOf('month')
          .format('YYYY-MM-DD')
      }

      let [searchRes, toolsRes] = await Promise.all([
        $axiosApi.getToolsSearchList({
          created_at_start: created_at_start,
          created_at_end: created_at_end,
          page: 1,
          per_page: 28,
          order_by: 'month_visited_count',
        }),
        $axiosApi.searchGetAd(),
        /* $axiosApi.getTools({
          page: 1,
          per_page: 100,
          history_has_recommended: 1,
        }), */
      ])

      let res = {}
      let toolsArr = []
      if (searchRes.code === 200) {
        res.new_list = searchRes.data.new_list
        res.toolsList = searchRes.data.data
        res.category_group_list = searchRes.data.category_group_list

        res.total = searchRes.data.total
        res.page = searchRes.data.current_page ? searchRes.data.current_page : 1
        res.next_page_url = searchRes.data.next_page_url
          ? searchRes.data.next_page_url
          : null

        res.tool_count = searchRes.data.tool_count
        res.category_count = searchRes.data.category_count

        function websiteName(tool) {
          let toolName = tool.name
          if (tool.website && tool.website && tool.website.name) {
            toolName = tool.website.name
          }
          return toolName
        }

        if (res.toolsList && res.toolsList.length > 0) {
          res.toolsList.forEach((item, key) => {
            if (key < 10) {
              toolsArr.push(websiteName(item))
            }
          })
        }
      } else {
        if (searchRes && searchRes.code && searchRes.code === 404) {
          error({ statusCode: 404 })
        } else if (!(searchRes && searchRes.code && searchRes.code === 401)) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: searchRes.code,
          })
        }
      }

      let recommendToolsList = []
      if (toolsRes.code === 200) {
        if (
          toolsRes.data.featured_list &&
          toolsRes.data.featured_list.length > 0
        ) {
          store.commit(
            'SET_TOP_ADVERTISER',
            JSON.parse(JSON.stringify(toolsRes.data.featured_list[0]))
          )
          let firstAd = toolsRes.data.featured_list.shift()
          let rIndex = res.toolsList.findIndex((item) => {
            return item.handle === firstAd.handle
          })
          if (rIndex !== -1) {
            res.toolsList.splice(rIndex, 1)
          }
          res.toolsList.unshift(firstAd)
        } else {
          store.commit('SET_TOP_ADVERTISER', null)
        }
        recommendToolsList =
          toolsRes.data.featured_list && toolsRes.data.featured_list.length > 0
            ? toolsRes.data.featured_list
            : []
      } else {
        store.commit('SET_TOP_ADVERTISER', null)
      }

      /* if (recommendRes.code === 200) {
        recommendToolsList =
          recommendRes.data.data && recommendRes.data.data.length > 0
            ? recommendRes.data.data
            : []
      } */

      let description = app.i18n.t('index_month_desc', {
        date: month,
        list: toolsArr.join(', '),
      })
      let title = app.i18n.t('index_month_title', { date: month })

      return {
        ...res,
        created_at_start,
        created_at_end,
        title,
        description,
        month,
        isYear,
        recommendToolsList,
        year,
      }
    } catch (err) {
      console.log(err)
    }
  },
  watch: {
    $route: {
      handler(route) {
        /* if (route.name === this.$route.name) {
          this.getList(1)
        } */
      },
      deep: true,
    },
  },
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      title: null,
      description: null,

      new_list: [],
      toolsList: [],
      category_group_list: [],
      page: 1,
      per_page: 28,
      next_page_url: null,
      loading: false,
      total: 0,
      month: null,
      isYear: false,

      tool_count: 0,
      category_count: 0,

      //第一次加载
      fLoading: false,
      sort: 'month_visited_count',
      sortOptions: {
        isShowOptions: false,
        options: [
          { label: 'index_sortMonthVisitedCount', val: 'month_visited_count' },
          { label: 'index_sortCreatedAt', val: 'created_at' },
          { label: 'index_sortCollectedCount', val: 'collected_count' },
        ],
      },

      recommendToolsList: [],

      year: null,
      fullYear: parseInt(new Date().getFullYear()),
    }
  },
  computed: {
    ...mapState({
      countries: (state) => state.countries,
      locale: (state) => state.locale,
    }),
  },
  mounted() {
    window.addEventListener('scroll', this.onSroll)
  },
  methods: {
    ...mapMutations(['SET_RetrackExposure']),
    onSroll() {
      //滚动条到底部的条件
      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
      //变量windowHeight是可视区的高度
      var windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight
      //变量scrollHeight是滚动条的总高度
      var scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight

      const end = document.querySelector('#end')
      const footerHeight = scrollHeight - (end.offsetTop + end.offsetHeight)

      //滚动条到底部的条件
      if (scrollTop + windowHeight + 1200 > scrollHeight - footerHeight) {
        if (this.next_page_url && !this.loading) {
          this.getList(this.page + 1)
        }
      }
    },
    async getList(page) {
      this.loading = true
      try {
        const res = await this.$axiosApi.getToolsSearchList({
          created_at_start: this.created_at_start,
          created_at_end: this.created_at_end,
          page: page,
          per_page: 28,
          order_by: this.sort,
        })

        this.loading = false

        if (res.code === 200) {
          if (page === 1) {
            this.toolsList = res.data.data
          } else {
            this.toolsList = this.toolsList.concat(res.data.data)
          }
          this.total = res.data.total ? res.data.total : 0
          this.page = res.data.current_page ? res.data.current_page : 1
          this.next_page_url = res.data.next_page_url
            ? res.data.next_page_url
            : null
          this.SET_RetrackExposure(Date.now())
        }
      } catch (error) {
        console.log('error')
        this.loading = false
      }
    },
    async toSearch(val) {
      this.fLoading = true
      this.sort = val
      this.sortOptions.isShowOptions = false
      await this.getList(1)
      this.fLoading = false
    },
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.onSroll, false)
  },
}
</script>
<style lang='scss' scoped>
.index-container {
  ::v-deep .el-loading-mask {
    svg {
      margin-left: auto;
      margin-right: auto;
    }
  }
}
</style>
